<template>
  <div class="p-4">
    <Row justify="space-between">
        <Col :span="10" class="TableOuterBox" style="height: calc(100vh - 160px)">
          <SwHeader :month="month" :direction="leftDir" :type="changeType" @changeMonth = "changeMonth" :bookNum="props.bookNum"/>
          <WaterLocation  :dataSourse="leftDataSourse" :direction="leftDir" @selectChange="selectChange" @initData = "initDataSourse"/>
          <TransferTable :dataSourse="leftDataSourse" :Column="Column" :size="tableSize" :pagination="paginationBl"
            @initData = "initDataSourse"
            :scroll="{ y: 500,x:900 }" :id="leftId" ref="leftRef" @setRows="setRows" @selectButtonDis="selectButtonDis"/>
        </Col>
        <Col :span="3" class="centerOperation">
          <CenterOperation @transferData="transferData" @changeRadio="changeRadio" :buttonList="buttonList" />
        </Col>
        <Col :span="10" class="TableOuterBox">
          <SwHeader :month="month" :direction="rightDir" :type="changeType" :optionsList="optionsList" @selectBook="selectBook"/>
          <WaterLocation :dataSourse="rightDataSourse" :direction="rightDir" @selectChange="selectChange" @initData = "initDataSourse"/>
          <TransferTable :dataSourse="rightDataSourse" :Column="Column" :size="tableSize" :id="rightId"
            @initData = "initDataSourse"
            @changeOrder="changeOrder"
            :pagination="paginationBl" :scroll="{ y: 500,x:900 }" :footerBl="true" ref="rightRef" @setRows="setRows"
            @selectButtonDis="selectButtonDis" />
        </Col>
    </Row>
  </div>
</template>
<script lang="ts" setup>
// import type { BasicColumn, BasicTableProps, CellFormat, GetColumnsParams } from '../types/table';
import type { sizeType, selectRowsType } from "./types/index"
import { ref, unref, watch, onMounted, toRefs } from 'vue';
import { Row, Col, message } from 'ant-design-vue';
import { pullAllBy, isEqual, cloneDeep } from "lodash-es";
import { trColumnFn, trDataSourceFn } from "./utils/data";
import { operationButton } from './enum/index';
import SwHeader from "./components/SwHeader.vue";
import WaterLocation from './components/WaterLocation.vue';
import CenterOperation from './components/CenterOperation.vue';
import TransferTable from './components/TransferTable.vue';
import { messageFn } from "/@/store/utils";

const leftRef = ref<any>(null);
const rightRef = ref<any>(null)

const props = defineProps<{
  columns: object[],//列描述数据对象
  leftData: object[],//左侧列表数据
  rightData: object[],//右侧列表数据
  order?: boolean | undefined,//是否显示排序字段
  key?: string,//key字段 -- 暂时无用
  month?: number|undefined, //月份---默认为单月1,非所有业务都要用到
  changeType : string,//区别是哪个业务,比如水表/表册
  bookNum? : number | string, //表册号
  optionsList?:object[],//表册下拉选项
  bookRightId?: string // 表册右侧编号id
}>()

const emits = defineEmits(['backFn','saveFn','changeMonth','selectBook']);

const { columns, order, month, leftData, rightData, bookNum,changeType } = props;
const { optionsList } = toRefs(props)
//type  //当此值为one的时候是水表对水表,为two的时候是表册对表册,保留扩展

const leftDataSourse = ref<object[]>(); //左侧数据集合
const rightDataSourse = ref<object[]>(); //左侧数据集合
const testKey = ref<string|undefined>("");
const Column = ref<object[]>(columns); //表头集合
const orderBl = ref<boolean | undefined>(order); //是否需要序号
const buttonList = ref<object[]>(operationButton);//左右按钮
const leftRows = ref<object[]>(); //左侧选中的列表
const rightRows = ref<object[]>();//右侧选中的列表
const tableSize = ref<sizeType>('small'); // 默认表格大小为最小 small|middle|defalut
const paginationBl = ref<boolean>(false); //是否展示页码
const leftId = ref<string>('left_id'); //左侧列表的id
const rightId = ref<string>('right_id');//右侧列表的id
const radioType = ref<number>(3);
const leftDir = ref<selectRowsType>('left');
const rightDir = ref<selectRowsType>('right');
const flag = ref(true) // 第一次赋值

if (orderBl) {
  Column.value = trColumnFn(columns); //增加序号
  orderBl.value = false;
}

const setTableData = () => {
  if (props.leftData && props.rightData) { //设置列表数据
    leftDataSourse.value = trDataSourceFn(props.leftData);
    rightDataSourse.value = trDataSourceFn(props.rightData);
    testKey.value = ''+Math.random();
  }
}
watch(props,(newValue,oldValue)=>{
  if (flag.value) {
    console.log('prop----',props.leftData, props.rightData);
    leftDataSourse.value = trDataSourceFn(props.leftData);
    rightDataSourse.value = trDataSourceFn(props.rightData);;
    testKey.value = ''+Math.random();
  }
},{deep:true});

watch(() => leftDataSourse.value, (n) => {
  console.log(n, 'nnnnnn');
  
},{deep: true})

const setRows = (type: selectRowsType, rows: object[]) => { //保存选中后的内容( 左右侧选中 )
  if (type === 'left') {
    leftRows.value = rows;
  } else {
    rightRows.value = rows;
  }
}

const selectButtonDis = (num: number, bl: boolean) => { //设置按钮状态
  buttonList.value[num].bBoolean = bl;
}

const transferData = (item: object) => { //左右移动数据方法
  if (changeType === 'CHANGE_BOOK' && !props.bookRightId) {
    return  messageFn('error', '请选择需要更换表册')
  }
  flag.value = false
  const leftLength = leftDataSourse.value?.length
  const rightLength = rightDataSourse.value?.length
  let index: number | undefined = undefined
  if (item.type === 'left' && radioType.value !== 3) {
    if (rightRows.value && rightRows.value[0]) {
      index = rightDataSourse.value?.findIndex(item => item?.user_meter_id === rightRows.value[0].user_meter_id) as number
    } else {
      return messageFn('error', '请先在已排水表列表中勾选一块水表')
    }
  } else if (item.type === 'right' && radioType.value !== 3) {
    if (leftRows.value && leftRows.value[0]) {
      console.log(leftRows.value, 'leftRows');
      
      index = leftDataSourse.value?.findIndex(item => item?.user_meter_id === leftRows.value[0].user_meter_id) as number
    } else {
      return messageFn('error', '请先在待排水表列表中勾选一块水表')
    }
  }
  switch (radioType.value) {
    case 1:
      leftAndRightTransType(item.type, index )
      break;
  
    case 2:
      leftAndRightTransType(item.type, index + 1)
      break;
  
    case 3:
      index = item.type === 'left' ? rightLength : leftLength
      leftAndRightTransType(item.type, index)
      break;
  
    default:
      break;
  }
  resetOptions();//清空|重置列表数据
  
}

const leftAndRightTransType = (type: string, index: number) => {
  if (type === 'left') { //从左往右
    if (rightRows.value?.length !== 1 && radioType.value !== 3 ) return messageFn('error', '请先在已排水表列表中勾选一块水表')
    // leftDataSourse.value = pullAllWith(leftDataSourse.value, leftRows.value, isEqual);
    leftDataSourse.value = pullAllBy(leftDataSourse.value, leftRows.value, 'user_meter_id');
    rightDataSourse.value?.splice(index, 0, ...leftRows.value);
  }
  if (type === 'right') { //从右往左
    if (leftRows.value?.length !== 1 && radioType.value !== 3) return messageFn('error', '请先在待排水表列表中勾选一块水表')
    rightDataSourse.value = pullAllBy(rightDataSourse.value, rightRows.value, 'user_meter_id');
    leftDataSourse.value?.splice(index, 0, ...rightRows.value);
  }
}


const resetOptions = () => { //清空|重置列表数据
  leftRef.value.setSelectedRowKeys(); //清空左侧选中列表
  rightRef.value.setSelectedRowKeys();//清空右侧选中列表
  rightRows.value = []
  leftRows.value = []
  leftDataSourse.value = orderHandle(unref(leftDataSourse)); // 处理左右数据转移后,序号不一致的问题
  rightDataSourse.value = orderHandle(unref(rightDataSourse)); //处理左右数据转移后,序号不一致的问题
  selectButtonDis(0, true); //初始化左侧按钮
  selectButtonDis(1, true); //初始化右侧按钮
}

const initDataSourse = ()=>{
  const leftList = cloneDeep(leftDataSourse.value);
  const rightList = cloneDeep(rightDataSourse.value);
  for(let i in leftList){
    leftList[i].SELECTBL = false;
  }
  for(let i in rightList){
    rightList[i].SELECTBL = false;
  }
  leftDataSourse.value = leftList;
  rightDataSourse.value = rightList;
}

// 移动当前行
const changeOrder = (e: any) => {
  const index: number = rightDataSourse.value?.findIndex(item => item?.user_meter_id === rightRows.value[0].user_meter_id) as number
  const length = rightDataSourse.value!.length - 1
  const { type } = e
  switch (type) {
    case 'up':
      orderData(index, index- 1)
      break;
    
    case 'down':
      if (index >=  length) return messageFn('error', '选择的项已经是最后一项，不可下移')
      orderData(index, index + 1)
      break;

    case 'top':
      if (index === 0) return messageFn('error', '选择的项已经在顶部')
      orderData(index, 0)
      break;

    case 'bottom':
      if (index === length) return messageFn('error', '选择的项已经在底部')
      orderData(index, length)
      break;

    default:
      break;
  }
  
}

const orderData = (first: number, second: number) => {
  if (rightDataSourse.value) {
    var tmp = rightDataSourse.value[second];
    rightDataSourse.value[second] = rightDataSourse.value[first];
    rightDataSourse.value[first] = tmp;
    trDataSourceFn(rightDataSourse.value)
  }
}

const orderHandle = (data: any) => { //处理左右数据转移后,序号不一致的问题
  const thisData = data;
  thisData.map((item: object, index: number) => {
    return item.ORDERNO = index + 1;
  })
  return thisData;
}

const changeRadio = (backNum: number) => { //确定选中左右切换的位置
  radioType.value = backNum;
}

const selectChange = (type:string,value:string)=>{
  let thisList:object[]|undefined = [];
  if(type === 'left'){
    thisList = cloneDeep(unref(leftDataSourse));
  }else{
    thisList = cloneDeep(unref(rightDataSourse))
  }
  for(let i in thisList){
    if(thisList[i].user_meter_code === value){
      thisList[i].SELECTBL = true;
    }else{
      thisList[i].SELECTBL = false;
    }
  }
  if(type === 'left'){
    leftDataSourse.value = thisList;
    leftRef.value.setSroll('left',thisList);
  }else{
    rightDataSourse.value = thisList;
    rightRef.value.setSroll('right',thisList);
  }
  

}

const saveDataFn = ()=>{
  console.log('saveDataFn--调用成功');
   emits("saveFn",changeType,unref(leftDataSourse),unref(rightDataSourse));
}

const changeMonth = (type:string,value:string)=>{
  console.log('changeMonth-22233--',value);
  flag.value = true
  setTableData()
  emits("changeMonth",type,value);
}

const selectBook = (type:string,value:string)=>{
  emits("selectBook",type,value);
}

onMounted(() => {
  setTableData()
})


defineExpose({
  saveDataFn
})
</script>

<style lang="less" scoped>
.TableOuterBox {
  border: 1px solid rgb(217, 217, 217);
  background-color: #FFFFFF;
}

.tRHeight {
  // height: 40rem;
  overflow: auto;
}

.centerOperation {
  // border:1px solid;
  padding: 0 !important;
  margin: 0 !important;
  text-align: center;
  position: relative;
  background-color: #FFFFFF;
}
</style>
